package com.sky.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.server.HttpServerResponse;
import cn.hutool.json.JSONUtil;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper  orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate  redisTemplate;

    @Autowired
    private WorkspaceService workspaceService;


    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        String key = "report:turnover:" +  begin+ ":" + end;
        if (redisTemplate.hasKey(key)) {
            // 获取缓存数据
            TurnoverReportVO v = (TurnoverReportVO)redisTemplate.opsForValue().get(key);
            return v;
        }
        log.info("开始查询日期区间{}~{}的营业数据...", begin, end);
        List<LocalDate> dateList = new ArrayList<>();
        for(LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            dateList.add(date);
        }
        List<Double> turnOverList = dateList.stream().map(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 当前时间已完成订单金额统计
            // select sum(amount) from orders where status = 5 and order_time >= ? and order_time < ?
            Map<String, Object> mp = new HashMap();
            mp.put("status", 5);
            mp.put("begin", beginTime);
            mp.put("end", endTime);
            Double turnOver = orderMapper.sumByMap(mp);
            if (turnOver == null) {
                turnOver = 0.0;
            }
            return turnOver;
        }).collect(Collectors.toList());

        TurnoverReportVO vo = TurnoverReportVO.builder()
                .dateList(StrUtil.join(",", dateList))
                .turnoverList(StrUtil.join(",", turnOverList))
                .build();
        redisTemplate.opsForValue().set(key, vo, 1, TimeUnit.DAYS);
        return vo;
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        String key = "report:user:" + begin + ":" + end;
        if (redisTemplate.hasKey(key)) {
            // 获取缓存数据
            return (UserReportVO)redisTemplate.opsForValue().get(key);
        }
        log.info("开始查询日期区间{}~{}的用户数据...", begin, end);
        List<LocalDate> dateList = new ArrayList<>();

        // select count(id) from user where create_time >= ? and create_time < ?
        List<Integer> newUserList = new ArrayList<>();

        // select count(id) from user where create_time < ?
        List<Integer> totalUserList = new ArrayList<>();

        for(LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map  = new HashMap();

            map.put("end", endTime);
            Integer totalUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);

            map.put("begin", beginTime);
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);

            dateList.add(date);
        }
        UserReportVO vo = UserReportVO.builder()
                .dateList(StrUtil.join(",", dateList))
                .totalUserList(StrUtil.join(",", totalUserList))
                .newUserList(StrUtil.join(",", newUserList))
                .build();
        redisTemplate.opsForValue().set(key, vo, 1, TimeUnit.DAYS);
        return vo;
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        String key = "report:order:" + begin + ":" + end;
        if(redisTemplate.hasKey(key)) {
            return (OrderReportVO) redisTemplate.opsForValue().get(key);
        }

        List<LocalDate> dateList = new ArrayList<>();
        // 每天订单总数
        List<Integer> orderCountList = new ArrayList<>();
        // 每天有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();

        for(LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map  = new HashMap();

            // 查询每天的订单总数
            // select count(id) from orders where order_time > begin and order_time < end
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer count = orderMapper.countByMap(map);
            orderCountList.add(count);

            // 查询每天的有效订单数
            // select count(id) from orders where order_time > begin and order_time < end and status = 5
            map.put("status", Orders.COMPLETED);
            Integer validCount = orderMapper.countByMap(map);
            validOrderCountList.add(validCount);

            dateList.add(date);
        }
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0) orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;

        OrderReportVO vo = OrderReportVO.builder()
                .dateList(StrUtil.join(",", dateList))
                .orderCountList(StrUtil.join(",", orderCountList))
                .validOrderCountList(StrUtil.join(",", validOrderCountList))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        redisTemplate.opsForValue().set(key, vo, 1, TimeUnit.DAYS);
        return vo;
    }

    @Override
    public SalesTop10ReportVO getTop10Statistics(LocalDate begin, LocalDate end) {
        String key = "report:top10:" + begin + ":" + end;
        if(redisTemplate.hasKey(key)) {
            return (SalesTop10ReportVO) redisTemplate.opsForValue().get(key);
        }
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        String nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.joining(","));
        String numberList = salesTop10.stream().map(x -> x.getNumber().toString()).collect(Collectors.joining(","));
        SalesTop10ReportVO vo = SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
        redisTemplate.opsForValue().set("report:salesTop10",vo, 1, TimeUnit.DAYS);
        return vo;

    }

    @Override
    public void exportBusinessData(HttpServletResponse response) throws IOException {
        // 1.查数据库获得最近30天营业数据
        LocalDate begin  = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        // 2.写入Excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook  excel = new XSSFWorkbook(in);
        // 3.获取sheet页
        XSSFSheet sheet = excel.getSheet("Sheet1");
        // 设置时间参数
        sheet.getRow(1).getCell(1).setCellValue("时间" + begin + "至" + end);

        sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
        sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
        sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());

        sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
        sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

        for(int i = 0; i < 30; i++) {
            LocalDate date = begin.plusDays(i);
            BusinessDataVO vo = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

            XSSFRow row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(vo.getTurnover());
            row.getCell(3).setCellValue(vo.getValidOrderCount());
            row.getCell(4).setCellValue(vo.getOrderCompletionRate());
            row.getCell(5).setCellValue(vo.getNewUsers());
        }

        // 4.导出文件
        OutputStream out = response.getOutputStream();
        excel.write(out);

        out.close();
        excel.close();
    }
}
